import json
import sys

def log(msg):
    with open('text/log.txt', 'a', encoding='utf-8') as f:
        f.write(str(msg) + '\n')

def load_json(filename):
    with open(filename, 'r', encoding='utf-8') as f:
        return json.load(f)

def build_entity_map(entities):
    return {e['uuid']: e for e in entities}

def build_parent_to_children(entities, associations):
    parent_to_children = {}
    for e in entities:
        if 'children' in e:
            parent_to_children.setdefault(e['uuid'], []).extend(e['children'])
    for a in associations:
        if a.get('type') == 'core:line_edge':
            parent = a.get('source')
            child = a.get('target')
            if parent and child:
                parent_to_children.setdefault(parent, []).append(child)
    return parent_to_children

def find_all_section_wrapped_nodes(entity_map):
    wrapped = set()
    for e in entity_map.values():
        if e.get('type') == 'core:section':
            for child_uuid in e.get('children', []):
                child = entity_map.get(child_uuid)
                if child and child.get('type') != 'core:section':
                    wrapped.add(child_uuid)
    return wrapped

def section_flatten(uuid, entity_map, wrapped_nodes):
    entity = entity_map[uuid]
    if entity.get('type') != 'core:section':
        return [uuid]
    children = entity.get('children', [])
    section_nodes = []
    normal_nodes = []
    for child_uuid in children:
        child = entity_map.get(child_uuid)
        if not child:
            continue
        if child.get('type') == 'core:section':
            section_nodes.append(child_uuid)
        elif child_uuid not in wrapped_nodes:
            normal_nodes.append(child_uuid)
    return section_nodes + normal_nodes

def get_structure_signature(uuid, entity_map, parent_to_children, path=None):
    if path is None:
        path = set()
    if uuid in path:
        return ''
    path = path | {uuid}
    children = parent_to_children.get(uuid, [])
    child_sigs = [get_structure_signature(child, entity_map, parent_to_children, path) for child in children]
    return f"{uuid}(" + "|".join(child_sigs) + ")"

def batch_dedup_and_expand(uuids, entity_map, parent_to_children, level=1):
    # 1. 批量生成本层所有节点的结构签名
    sig_map = {u: get_structure_signature(u, entity_map, parent_to_children) for u in uuids}
    log(f"[分层去重] level={level} 本层节点: {uuids}")
    log(f"[分层去重] 本层结构签名: {sig_map}")
    # 2. 做同层最大结构去重（只在本分支内比对）
    keep_uuids = list(uuids)
    for u1 in uuids:
        for u2 in uuids:
            if u1 == u2:
                continue
            if sig_map[u1] in sig_map[u2]:
                if u1 in keep_uuids:
                    keep_uuids.remove(u1)
                    log(f"[分层去重] {u1} 结构被 {u2} 完全包含，去重")
                break
    # 3. 递归展开，拼接 Markdown
    md = ''
    wrapped_nodes = find_all_section_wrapped_nodes(entity_map)
    for uuid in keep_uuids:
        entity = entity_map[uuid]
        text = entity.get('text') or ''
        type_ = entity.get('type') or ''
        if level <= 6:
            prefix = '#' * level + ' '
        else:
            prefix = '  ' * (level - 6) + '- '
        md += f"{prefix}[{uuid}] {text}\n"
        # 分组节点递归children
        if type_ == 'core:section':
            children = section_flatten(uuid, entity_map, wrapped_nodes)
            if children:
                log(f"[递归] level={level+1} 分组节点 {uuid} 递归 children: {children}")
                md += batch_dedup_and_expand(children, entity_map, parent_to_children, level+1)
        # 普通节点递归children
        children = parent_to_children.get(uuid, [])
        if children:
            log(f"[递归] level={level+1} 普通节点 {uuid} 递归 children: {children}")
            md += batch_dedup_and_expand(children, entity_map, parent_to_children, level+1)
    return md

def main():
    # 解析命令行参数
    if len(sys.argv) >= 3:
        input_json = sys.argv[1]
        output_md = sys.argv[2]
    else:
        input_json = 'text/开始界面-正文.json'
        output_md = 'text/开始界面-正文.md'
    # 清空日志
    with open('text/log.txt', 'w', encoding='utf-8') as f:
        f.write('')
    data = load_json(input_json)
    entities = data['entities']
    associations = data.get('associations', [])
    entity_map = build_entity_map(entities)
    parent_to_children = build_parent_to_children(entities, associations)
    log('所有节点text:')
    for e in entities:
        log(e.get('text'))
    # 自动寻找根节点
    root = None
    for e in entities:
        if e.get('type') == 'core:section':
            root = e
            break
    if not root:
        log('未找到根节点')
        return
    root_children = parent_to_children.get(root['uuid'], [])
    md = f"# [{root['uuid']}] {root['text']}\n"
    md += batch_dedup_and_expand(root_children, entity_map, parent_to_children, level=2)
    with open(output_md, 'w', encoding='utf-8') as f:
        f.write(md)
    log(f'已生成: {output_md}')

if __name__ == '__main__':
    main() 